package com.example.aitoedu.controller;

import cn.dev33.satoken.stp.StpUtil;
import com.example.aitoedu.entity.TsTalk;
import com.example.aitoedu.mapper.TsTalkMapper;
import jakarta.websocket.*;
import jakarta.websocket.server.PathParam;
import jakarta.websocket.server.ServerEndpoint;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.time.LocalDateTime;
import java.util.concurrent.ConcurrentHashMap;

@Slf4j
@Component
@ServerEndpoint("/user/talk/{satoken}")
public class WebSocketController {

    private static ConcurrentHashMap<Long, WebSocketController> clients = new ConcurrentHashMap<>();

    private Session session;

    private Long userId;

    private static TsTalkMapper tsTalkMapper;

    @Autowired
    public void setTsTalkMapper(TsTalkMapper tsTalkMapper){
        WebSocketController.tsTalkMapper = tsTalkMapper;
    }

    @OnOpen
    public void onOpen(Session session, @PathParam("satoken")String satoken){
        System.out.println("websocket的satoken："+satoken);
        this.session = session;
        this.userId = Long.valueOf((String) StpUtil.getLoginIdByToken(satoken));
        System.out.println("进入聊天室的id:"+this.userId);
        clients.put(userId, this);
    }

    @OnMessage
    public void onMessage(String message,Session session,@PathParam("satoken")String satoken) {
        System.out.println("前端发过来的信息："+message);
        Long to = Long.valueOf(message.split(",")[0]);
        String from = (String) StpUtil.getLoginIdByToken(satoken);
        String msg = message.split(",")[1];
        try {
            WebSocketController webSocketController = clients.get(to);
            if(webSocketController != null){
                webSocketController.session.getBasicRemote().sendText(from+","+msg);
            }
            TsTalk tsTalk = TsTalk.builder()
                    .content(msg)
                    .isRead(0)
                    .receiver(to)
                    .sender(Long.valueOf(from))
                    .createTime(LocalDateTime.now())
                    .build();
            tsTalkMapper.insert(tsTalk);
        }catch (IOException e){
            log.error(e.getMessage());
        }
    }
    @OnClose
    public void onClose(Session session, @PathParam("satoken")String satoken){
        clients.remove(this.userId);
    }

    @OnError
    public void onError(Session session, Throwable error){
        log.error("发生错误");
        error.printStackTrace();
    }
}
